import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { propertyApi } from '@/api'
import type { Property, PropertyCreate, PropertyUpdate } from '@/api/types'
import notify from '@/utils/notify'

/**
 * 房源 Store
 *
 * Vue3 Composition API 风格的 Pinia Store
 * 两种实现方式对比：
 *
 * 1. Setup Store（本实现）- 推荐
 *    优点: 更灵活，类似 Composition API，代码组织更自由
 *    缺点: 需要显式 return
 *
 * 2. Options Store
 *    优点: 类似 Vue2，熟悉的 state/getters/actions 结构
 *    缺点: 相对不够灵活
 */
export const usePropertyStore = defineStore('property', () => {
  // ========== State（使用 ref/reactive）==========
  const properties = ref<Property[]>([])
  const currentProperty = ref<Property | null>(null)
  const total = ref(0)
  const loading = ref(false)

  // ========== Getters（使用 computed）==========
  const vacantProperties = computed(() =>
    properties.value.filter((p: Property) => p.status === 'vacant')
  )

  const rentedProperties = computed(() =>
    properties.value.filter((p: Property) => p.status === 'rented')
  )

  const averageRent = computed(() => {
    if (properties.value.length === 0) return 0
    const sum = properties.value.reduce((acc: number, p: Property) => acc + p.rent_price, 0)
    return Math.round(sum / properties.value.length)
  })

  // ========== Actions（普通函数）==========

  /**
   * 获取房源列表
   */
  async function fetchProperties(
    params: {
      page: number
      page_size: number
      name?: string
      address?: string
      status?: string
    } = { page: 1, page_size: 10 }
  ) {
    loading.value = true
    try {
      const res = await propertyApi.getList(params)
      properties.value = res.items
      total.value = res.total
      return res
    } catch (error) {
      console.error('获取房源列表失败', error)
      notify.error('获取房源列表失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取房源详情
   */
  async function fetchProperty(id: number) {
    loading.value = true
    try {
      const res = await propertyApi.getById(id)
      currentProperty.value = res
      return res
    } catch (error) {
      console.error('获取房源详情失败', error)
      notify.error('获取房源详情失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 创建房源
   */
  async function createProperty(data: PropertyCreate) {
    loading.value = true
    try {
      const res = await propertyApi.create(data)
      notify.success('创建房源成功')
      return res
    } catch (error) {
      console.error('创建房源失败', error)
      notify.error('创建房源失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新房源
   */
  async function updateProperty(id: number, data: PropertyUpdate) {
    loading.value = true
    try {
      const res = await propertyApi.update(id, data)
      notify.success('更新房源成功')
      return res
    } catch (error) {
      console.error('更新房源失败', error)
      notify.error('更新房源失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除房源
   */
  async function deleteProperty(id: number) {
    loading.value = true
    try {
      const res = await propertyApi.delete(id)
      notify.success('删除房源成功')
      return res
    } catch (error) {
      console.error('删除房源失败', error)
      notify.error('删除房源失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量删除房源（优化版：使用批量接口）
   */
  async function deleteProperties(ids: number[]) {
    loading.value = true
    try {
      // ✅ P1-1修复: 使用批量删除API（1次请求）替代循环（N次请求）
      if (propertyApi.bulkDelete) {
        const result = await propertyApi.bulkDelete(ids)
        notify.success(result.message || '批量删除房源成功')
        return result
      }

      // 降级方案：如果API不支持批量删除，使用循环
      const promises = ids.map(id => propertyApi.delete(id))
      const res = await Promise.all(promises)
      notify.success('批量删除房源成功')
      return res
    } catch (error) {
      console.error('批量删除房源失败', error)
      notify.error('批量删除房源失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 恢复单个已删除房源
   */
  async function restoreProperty(id: number) {
    if (!propertyApi.restore) {
      notify.error('该功能不支持恢复操作')
      return null
    }

    loading.value = true
    try {
      const res = await propertyApi.restore(id)
      notify.success('恢复房源成功')
      return res
    } catch (error) {
      console.error('恢复房源失败', error)
      notify.error('恢复房源失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 批量恢复已删除房源
   */
  async function restoreProperties(ids: number[]) {
    if (!propertyApi.bulkRestore) {
      notify.error('该功能不支持批量恢复操作')
      return null
    }

    loading.value = true
    try {
      const result = await propertyApi.bulkRestore(ids)
      notify.success(result.message || '批量恢复房源成功')
      return result
    } catch (error) {
      console.error('批量恢复房源失败', error)
      notify.error('批量恢复房源失败')
      return null
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取已删除房源列表
   */
  async function fetchDeletedProperties(
    params: {
      page: number
      page_size: number
      name?: string
      address?: string
    } = { page: 1, page_size: 10 }
  ) {
    if (!propertyApi.getDeletedList) {
      notify.error('该功能不支持查询已删除记录')
      return null
    }

    loading.value = true
    try {
      const res = await propertyApi.getDeletedList(params)
      properties.value = res.items
      total.value = res.total
      return res
    } catch (error) {
      console.error('获取已删除房源列表失败', error)
      notify.error('获取已删除房源列表失败')
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    // State
    properties,
    currentProperty,
    total,
    loading,

    // Getters
    vacantProperties,
    rentedProperties,
    averageRent,

    // Actions
    fetchProperties,
    fetchProperty,
    createProperty,
    updateProperty,
    deleteProperty,
    deleteProperties,

    // ✅ P1修复: 新增恢复和已删除列表功能
    restoreProperty,
    restoreProperties,
    fetchDeletedProperties,
  }
})
